package com.sisi.web;


import entity.Student;
import util.JavaUtil;

import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

@WebServlet("/hello")
public class Hello extends HttpServlet {

    @Override
    public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {
        System.out.println("Hello.service");

        Connection connection = null;
        PreparedStatement statement = null;
        ResultSet resultSet = null;
        ArrayList<Student> list = new ArrayList<>();
        try {
            connection = JavaUtil.getConnection();
            String sql = "SELECT id,name,age,gender FROM student";
            statement = connection.prepareStatement(sql);
            resultSet = statement.executeQuery();
            while (resultSet.next()) {
                // 每遍历一次循环，就拿出数据库查询结果里面的一行记录，就是一个学生的信息,
                // 就可以封装成一个Student对象
                int id = resultSet.getInt("id");
                String name = resultSet.getString("name");
                int age = resultSet.getInt("age");
                String gender = resultSet.getString("gender");
                Student student = new Student(id, name, age, gender);
                list.add(student);
            }
             for (Student student : list) {
                System.out.println(student);
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally {
            JavaUtil.close(connection, statement ,resultSet);
        }

        //将list数据放到一块内存区域中
        req.setAttribute("list",list);
        //跳转到jsp页面进行展示，dispatcher分发，forward转发
        req.getRequestDispatcher("/student_list.jsp").forward(req,res);
    }
}
